<?php
/**
 * (logic) Payment销售额-FBA费用
 */
namespace App\Logic\MonthlyReport\FbaFee;

use App\Models\Basics\SysPlatAccount;
use App\Models\Basics\SysCountry;
use App\Models\Basics\SysArea;
use App\Models\MonthlyReport\Payment\PaymentFBAFee;
use App\Models\MonthlyReport\Tmp\TmpPSales;
use Illuminate\Support\Str;
class PaymentSalesToFBAFee
{
    public static function exe(){
        ini_set('memory_limit', '200M');
        set_time_limit(0);
        $date = date('Y-m-01',strtotime('midnight first day of -1 month'));
        $country = [];
        TmpPSales::query()
            ->where('report_date',$date)
            ->where('type','Order')
            ->whereNotNull('sku')
            ->where('quantity',1)
            ->where('fba_fees','<>',0)
            ->orderBy('id')
            ->chunk(2000, function ($lines) use (&$country,$date){
                foreach ($lines as $line){
                    if(!array_key_exists($line->country,$country)){
                        $countryId = SysCountry::getIdByCountry($line->country);
                        $country[$line->country] = $countryId ?: 0;
                    }
                    //（正式）FBA费用
                    PaymentFBAFee::query()->create([
                        'report_date' => $date,
                        'country' => $line->country,
                        'country_id' => $country[$line->country],
                        'order_id' => $line->order_id,
                        'sku' => $line->sku,
                        'fba_fees' => $line->fba_fees]);
                }
            });
    }

    private static function _getAccountId($accountStr){
        $account = self::_getAccount($accountStr);
        return SysPlatAccount::getIdByAccount($account);
    }

    private static function _getAccount($accountStr){
        $str = self::_replaceB2B($accountStr);
        $pos = strripos($str,'-');
        if(!$pos){
            return '0';
        }
        $prefix = substr($str,0,$pos);
        $countryStr = substr($str,$pos+1);
        if($countryStr == 'EU'){
            return $str;
        }else{
            if(in_array($countryStr,SysArea::$_NACountryForAccount)){
                $suffix = 'NA';
            }elseif(in_array($countryStr,SysArea::$_EUCountryForAccount)){
                $suffix = 'EU';
            }else{
                $suffix = $countryStr;
            }
            return $prefix.'-'.$suffix;
        }
    }

    private static function _replaceB2B($str){
        if(Str::endsWith($str,'B2B')){
            $pos = strripos($str,'B2B');
            $str = substr($str,0,$pos);
        }
        return $str;
    }
}
